package jin.chen.service.impl;

import jin.chen.mapper.StuMapper;
import jin.chen.pojo.Stu;
import jin.chen.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

@Service
public class StuServiceImpl implements StuService {

    @Autowired
    private StuMapper stuMapper;

    @Override
    public Stu getId(Integer id) {

//        Example example = new Example(Stu.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo(id);
//        return stuMapper.selectOneByExample(example);
//        return stuMapper.getById(id);
        return stuMapper.selectByPrimaryKey(id);
    }

    @Override
    public int insertStu(Stu stu) {
        return stuMapper.insertStu(stu);
    }

    @Override
    public int deleteById(Integer id) {
        return stuMapper.deleteById(id);
    }

    @Override
    public void insertParent() {
        Stu stu = new Stu();
        stu.setName("parent");
        stu.setAge(12);
        stuMapper.insertStu(stu);
    }

    @Transactional(propagation = Propagation.NESTED)
    @Override
    public void insertSon() {
        insertSon1();
        int a = 1/0;
        insertSon2();

    }

    public int insertSon1() {
        Stu stu = new Stu();
        stu.setName("child-1");
        stu.setAge(2);
        return stuMapper.insertStu(stu);
    }

    public int insertSon2() {
        Stu stu = new Stu();
        stu.setName("child-2");
        stu.setAge(2);
        return stuMapper.insertStu(stu);
    }
}
